package cn.always.xiajia.framework.security.core.handler;

import java.io.IOException;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.http.MediaType;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.security.web.access.ExceptionTranslationFilter;

import cn.always.xiajia.framework.common.exception.enums.GlobalErrorCodeConstants;
import cn.always.xiajia.framework.common.exception.util.ServiceExceptionUtil;
import cn.always.xiajia.framework.common.util.ExtServletUtil;
import cn.always.xiajia.framework.security.core.util.SecurityFrameworkUtils;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;

/**
 * 访问一个需要认证的 URL 资源，已经认证（登录）但是没有权限的情况下，返回
 * {@link GlobalErrorCodeConstants#FORBIDDEN} 错误码。
 *
 * 补充：Spring Security 通过
 * {@link ExceptionTranslationFilter#handleAccessDeniedException(HttpServletRequest, HttpServletResponse, FilterChain, AccessDeniedException)}
 * 方法，调用当前类
 *
 * @author xgj
 *
 */
@Slf4j
@SuppressWarnings("JavadocReference")
public class AccessDeniedHandlerImpl implements AccessDeniedHandler {

	@Override
	public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException e)
			throws IOException, ServletException {
		// 打印 warn 的原因是，不定期合并 warn，看看有没恶意破坏
		log.warn("[commence][访问 URL({}) 时，用户ID({}) 用户编码({}) 权限不够]", request.getRequestURI(), SecurityFrameworkUtils.getLoginUserId(),
				SecurityFrameworkUtils.getLoginUserCode(), e);
		// 返回 403
		// 必须使用 APPLICATION_JSON_UTF8_VALUE，否则会乱码
		ExtServletUtil.write(response, JSONUtil.toJsonStr(ServiceExceptionUtil.exceptionF(GlobalErrorCodeConstants.FORBIDDEN)),
				MediaType.APPLICATION_JSON_UTF8_VALUE);
	}

}
